# -*- coding:utf-8 -*-
"""
Created on 26 aug 2012

@author: Olof Manbo
"""

from google.appengine.ext import webapp
from django.utils import simplejson
from google.appengine.api import channel

import logging
import re
import time

import requests
import test_pb2
import contour

class Page(webapp.RequestHandler):
    def get(self):


        html = """
        <!DOCTYPE html>
        <html>
          <head>
          <title>Fursten goes data</title>
          <link type="text/css" rel="stylesheet" href="/stylesheets/diagram.css" />
          <style id="node_style">
          </style>
          <script type="text/javascript" src="/_ah/channel/jsapi"></script>
          <script src="http://d3js.org/d3.v2.js"></script>
          <script src="http://underscorejs.org/underscore-min.js"></script>
          <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
          <script src="js/diagram.js"></script>
          <script src="/js/channel.js"></script>
          <script src="/js/mouse.js"></script>
          </head>
          <body onload="run_it('%s');">
          <div id="top">
            <div id="buttons">
              <button type="submit" name="startbutton" onclick="animate_start();">STARTA</button>
              <button type="submit" name="stopbutton" onclick="animate_stop();">STOPPA</button>
              <button type="submit" name="stepbutton" onclick="animate_step();">STEGA</button>
              <button type="submit" name="stepbutton" onclick="redraw();">RITA</button>
              <input type="text" id="simulator_address" value="localhost:8888"></input>
              <button type="submit" name="startbutton" onclick="init_button();">LADDA</button>
            </div>
              <div id="show_node_name">INGET</div>
            </div>
            </div>
            <div id="totaldata">
              <svg id="graph"></svg>
              <svg id="map"></svg>
            </div>           
          </body>
        </html>
        """
        

        token = channel.create_channel("HUMMER")
        html = html%(token)
        
        
        self.response.out.write(html)             

class GetResourceNamesAndCss(webapp.RequestHandler):
    def get(self):
        stuff = requests.sendResourceXmlRequest(self.request.get('address'))
        cssdata = requests.sendFurstenCssRequest(self.request.get('address'))
        
        for line in cssdata.splitlines():
            m = re.match(r"#(.*)\{.*color:(#.{6}).*", line)
            if (m is not None):
                cssdata += "\n#line_%s{stroke: %s;}"%(m.group(1), m.group(2))
            m = re.match(r"\.(.*?)-.*border-color:(#.{6}).*color:(#.{6}).*", line)    
            if (m is not None):
                cssdata += "\n.node_%s{stroke: %s; fill: %s;}"%(m.group(1), m.group(2), m.group(3))

        data = simplejson.dumps({"resource_names": sorted(stuff.values()), "css": cssdata})
        self.response.out.write(data)

class GetNextTick(webapp.RequestHandler):
    def post(self): #post due to URI being too long for get 
        logging.info(self.request.arguments())
        logging.info(self.request.get('tick'))
        logging.info(self.request.get_all('resources[]'))
            
        if self.request.get('tick') == "true":
            requests.sendProcessRequest(self.request.get('address'), test_pb2.ProcessRequest.RUN, "Run")
            
        stuff = requests.sendResourceXmlRequest(self.request.get('address'))
        nodeResponse = requests.sendNodeRequest(self.request.get('address'))
        nodes = {}
        for node in nodeResponse.node:
            key = stuff[node.resource_key]
            if nodes.has_key(key):
                nodes[key].append([node.x, node.y])
            else:
                nodes[key] = [[node.x, node.y]]
        logging.info(nodes)
        paths = self.createSvgMap(self.request.get_all('resources[]'), self.request.get('address'))
        data =  simplejson.dumps({"nodes": nodes, "paths": paths})
        self.response.out.write(data)


    def createSvgMap(self, resources, address):
        SCALE = 200
        X=range(-50,50)
        Y=range(-50,50)
        allNodes = getNodes(address)
        #node_names = ["vegetation_24trees", "vegetation_24grass", "animals_cattle"]
        resources_with_nodes = [resource_name for resource_name in resources if allNodes.has_key(resource_name)]
        nodes = [allNodes[resource_name] for resource_name in resources_with_nodes]
        paths, debug_dummy = contour.getPaths(SCALE, nodes, resources_with_nodes , X, Y)
        for p in paths:
            logging.info(p)
        return paths
        
def getNodes(address):
    stuff = requests.sendResourceXmlRequest(address)
    logging.info(stuff)
    nodeResponse = requests.sendNodeRequest(address)
    nodes = {}
    for node in nodeResponse.node:
        key = stuff[node.resource_key]
        if nodes.has_key(key):
            nodes[key].append([node.x, node.y])
        else:
            nodes[key] = [[node.x, node.y]]
    return nodes

class RequestMap(webapp.RequestHandler):
    def post(self):
        channel.send_message("HUMMER", "GET MAP")
        
class ChannelReady(webapp.RequestHandler):
    def post(self):
        channel.send_message("HUMMER", "SERVER ACK")